<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>邮件群发管理</title>
    <!--                       CSS                       -->
    <!-- Reset Stylesheet -->
    <link rel="stylesheet" href="/back/css/reset.css" type="text/css" media="screen" />
    <!-- Main Stylesheet -->
    <link rel="stylesheet" href="/back/css/style.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/back/css/invalid.css" type="text/css" media="screen" />
    <!--                       Javascripts                       -->
    <!-- jQuery -->
    <script type="text/javascript" src="/back/scripts/jquery-2.1.0.min.js"></script>
    <!-- jQuery Configuration -->
    <script type="text/javascript" src="/back/scripts/simpla.jquery.configuration.js"></script>
    <!-- Facebox jQuery Plugin -->
    <script type="text/javascript" src="/back/scripts/facebox.js"></script>
    
    <!-- 引入富文本编辑器 -->
    <link rel="stylesheet" type="text/css" href="/back/widget/dist/bootstrap.css">
    <link href="/back/widget/dist/summernote.css" rel="stylesheet"/>
    <script src="/back/widget/dist/bootstrap.js"></script>
    <script src="/back/widget/dist/summernote.js"></script>
    <script src="/back/widget/dist/lang/summernote-zh-CN.js"></script>
    
    <!-- 引入文件上传组件 -->
    <link rel="stylesheet" type="text/css" href="/back/widget/webuploader/webuploader.css">
    <script type="text/javascript" src="/back/widget/webuploader/webuploader.min.js"></script>

    
    <style>
        .mail-form {
            background: #fff;
            padding: 20px;
            margin: 20px 0;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input, 
        .form-group textarea, 
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
            font-size: 14px;
        }
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        .content-editor {
            height: 200px;
        }
        .recipients-area {
            height: 150px;
        }
        .btn {
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover {
            background: #45a049;
        }
        .btn-danger {
            background: #f44336;
        }
        .btn-danger:hover {
            background: #da190b;
        }
        .btn-info {
            background: #2196F3;
        }
        .btn-info:hover {
            background: #0b7dda;
        }
        .task-list {
            margin-top: 30px;
        }
        .task-item {
            background: #fff;
            margin: 10px 0;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            border-left: 4px solid #4CAF50;
        }
        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .task-title {
            font-size: 16px;
            font-weight: bold;
        }
        .task-status {
            padding: 4px 8px;
            border-radius: 3px;
            color: white;
            font-size: 12px;
        }
        .status-pending { background: #ff9800; }
        .status-sending { background: #2196F3; }
        .status-retrying { background: #9c27b0; }
        .status-completed { background: #4CAF50; }
        .status-cancelled { background: #9e9e9e; }
        .status-failed { background: #f44336; }
        .task-meta {
            color: #666;
            font-size: 12px;
            margin-bottom: 10px;
        }
        .task-progress {
            margin: 10px 0;
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background: #4CAF50;
            transition: width 0.3s ease;
        }
        .task-actions {
            margin-top: 10px;
        }
        .help-text {
            color: #666;
            font-size: 12px;
            margin-top: 5px;
        }
        
        /* 附件上传样式 */
        #attachmentUploader {
            border: 2px dashed #ddd;
            padding: 20px;
            text-align: center;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        
        #attachmentPicker {
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            display: inline-block;
            margin-bottom: 10px;
        }
        
        #attachmentPicker:hover {
            background: #45a049;
        }
        
        .attachment-item {
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 3px;
            padding: 10px;
            margin: 5px 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .attachment-info {
            flex: 1;
            text-align: left;
        }
        
        .attachment-name {
            font-weight: bold;
            color: #333;
        }
        
        .attachment-size {
            color: #666;
            font-size: 12px;
        }
        
        .attachment-remove {
            background: #f44336;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .attachment-remove:hover {
            background: #da190b;
        }
    </style>
</head>
<body>
    <div id="body-wrapper">
        <div id="sidebar-wrapper"></div>
        <div id="main-content">
            <div id="body">
                <h1>邮件群发管理</h1>
                
                <!-- 创建新任务表单 -->
                <div class="mail-form">
                    <h2>创建邮件群发任务</h2>
                    <form id="mailForm">
                        <div class="form-group">
                            <label for="batchName">任务名称:</label>
                            <input type="text" id="batchName" name="batchName" required>
                            <div class="help-text">为此次群发任务起一个便于识别的名称</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="senderConfig">发送方配置:</label>
                            <select id="senderConfig" name="senderConfig" required>
                                <option value="">请选择发送方配置</option>
                            </select>
                            <div class="help-text">选择用于发送邮件的发送方配置</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="senderName">发送者姓名:</label>
                            <input type="text" id="senderName" name="senderName" required>
                            <div class="help-text">收件人看到的发送者姓名</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="subject">邮件主题:</label>
                            <input type="text" id="subject" name="subject" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="content">邮件内容:</label>
                            <div id="mailContentEditor"></div>
                            <input type="hidden" id="content" name="content" required>
                            <div class="help-text">支持HTML格式的富文本内容</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="attachments">邮件附件:</label>
                            <div id="attachmentUploader">
                                <div id="attachmentList"></div>
                                <div id="attachmentPicker">选择文件</div>
                            </div>
                            <div class="help-text">可以上传多个附件，单个文件大小不超过10MB</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="recipients">收件人列表:</label>
                            <textarea id="recipients" name="recipients" class="recipients-area" required 
                                placeholder="请输入收件人信息，每行一个，格式：邮箱地址,姓名（可选）&#10;例如：&#10;john@example.com,John Doe&#10;jane@example.com&#10;最多支持100个收件人"></textarea>
                            <div class="help-text">每行一个收件人，格式：邮箱地址,姓名（姓名可选）。最多支持100个收件人。</div>
                        </div>
                        
                        <div class="form-group">
                            <button type="button" class="btn" onclick="createBatchTask()">创建任务</button>
                            <button type="button" class="btn btn-info" onclick="loadTaskList()">刷新列表</button>
                        </div>
                    </form>
                </div>
                
                <!-- 任务列表 -->
                <div class="task-list">
                    <h2>邮件群发任务列表</h2>
                    <div id="taskList">
                        <!-- 任务列表将在这里动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 初始化富文本编辑器
            initMailContentEditor();
            
            // 初始化附件上传组件
            initAttachmentUploader();
            
            // 加载发送方配置列表
            loadSenderConfigs();
            
            // 页面加载时获取任务列表
            loadTaskList();
            
            // 每30秒自动刷新一次任务列表
            setInterval(loadTaskList, 30000);
        });
        
        // 全局变量存储附件列表
        var attachmentList = [];
        
        // 加载发送方配置列表
        function loadSenderConfigs() {
            $.get('/api/mail/sender/enabled', function(response) {
                if (response.code === 200) {
                    var configs = response.data;
                    var select = $('#senderConfig');
                    select.empty();
                    select.append('<option value="">请选择发送方配置</option>');
                    
                    configs.forEach(function(config) {
                        if (config.status) { // 只显示启用的配置
                            var optionText = config.configName + ' (' + config.senderEmail + ')';
                            var option = $('<option></option>').attr('value', config.id).text(optionText);
                            if (config.isDefault) {
                                option.attr('selected', 'selected');
                            }
                            select.append(option);
                        }
                    });
                    
                    // 监听发送方配置选择变化
                    $('#senderConfig').change(function() {
                        var selectedConfigId = $(this).val();
                        if (selectedConfigId) {
                            var selectedConfig = configs.find(c => c.id == selectedConfigId);
                            if (selectedConfig && selectedConfig.senderName) {
                                $('#senderName').val(selectedConfig.senderName);
                            }
                        }
                    });
                } else {
                    console.error('加载发送方配置列表失败：' + response.message);
                }
            }).fail(function() {
                console.error('加载发送方配置列表时发生错误');
            });
        }
        
        // 初始化富文本编辑器
        function initMailContentEditor() {
            $('#mailContentEditor').summernote({
                placeholder: '请输入邮件内容...',
                height: 300,
                lang: 'zh-CN',
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']],
                    ['fontname', ['fontname']],
                    ['fontsize', ['fontsize']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['height', ['height']],
                    ['table', ['table']],
                    ['insert', ['link', 'picture', 'hr']],
                    ['view', ['fullscreen', 'codeview']],
                    ['help', ['help']]
                ],
                callbacks: {
                    onImageUpload: function(files) {
                        // 处理图片上传
                        uploadImageToEditor(files[0]);
                    }
                }
            });
        }
        
        // 初始化附件上传组件
        function initAttachmentUploader() {
            if (typeof WebUploader === 'undefined') {
                console.warn('WebUploader 组件未加载，使用备用上传方式');
                initFallbackUploader();
                return;
            }
            
            var uploader = WebUploader.create({
                auto: true,
                swf: '/back/widget/webuploader/Uploader.swf',
                server: '/api/file/upload',
                pick: '#attachmentPicker',
                accept: {
                    title: 'Files',
                    extensions: 'doc,docx,pdf,txt,xls,xlsx,ppt,pptx,zip,rar,jpg,jpeg,png,gif',
                    mimeTypes: 'application/*,text/*,image/*'
                },
                fileSizeLimit: 10 * 1024 * 1024, // 10MB
                fileSingleSizeLimit: 10 * 1024 * 1024 // 10MB
            });
            
            uploader.on('fileQueued', function(file) {
                addAttachmentToList(file.name, file.size, null, 'uploading');
            });
            
            uploader.on('uploadSuccess', function(file, response) {
                if (response.code === 200) {
                    updateAttachmentStatus(file.name, response.data, 'success');
                    attachmentList.push({
                        fileName: file.name,
                        filePath: response.data,
                        fileSize: file.size,
                        contentType: file.type
                    });
                } else {
                    updateAttachmentStatus(file.name, null, 'error');
                    alert('上传失败：' + response.message);
                }
            });
            
            uploader.on('uploadError', function(file) {
                updateAttachmentStatus(file.name, null, 'error');
                alert('上传失败，请重试');
            });
        }
        
        // 备用上传方式（当WebUploader不可用时）
        function initFallbackUploader() {
            $('#attachmentPicker').html('<input type="file" id="fileInput" multiple style="display: none;"><span>选择文件</span>');
            
            $('#attachmentPicker').click(function() {
                $('#fileInput').click();
            });
            
            $('#fileInput').change(function() {
                var files = this.files;
                for (var i = 0; i < files.length; i++) {
                    uploadFileWithFallback(files[i]);
                }
            });
        }
        
        // 备用上传方法
        function uploadFileWithFallback(file) {
            if (file.size > 10 * 1024 * 1024) {
                alert('文件大小不能超过10MB');
                return;
            }
            
            addAttachmentToList(file.name, file.size, null, 'uploading');
            
            var formData = new FormData();
            formData.append('file', file);
            
            $.ajax({
                url: '/api/file/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.code === 200) {
                        updateAttachmentStatus(file.name, response.data, 'success');
                        attachmentList.push({
                            fileName: file.name,
                            filePath: response.data,
                            fileSize: file.size,
                            contentType: file.type
                        });
                    } else {
                        updateAttachmentStatus(file.name, null, 'error');
                        alert('上传失败：' + response.message);
                    }
                },
                error: function() {
                    updateAttachmentStatus(file.name, null, 'error');
                    alert('上传失败，请重试');
                }
            });
        }
        
        // 上传图片到编辑器
        function uploadImageToEditor(file) {
            var formData = new FormData();
            formData.append('file', file);
            
            $.ajax({
                url: '/api/file/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.code === 200) {
                        // 获取当前页面的基础URL
                        var baseUrl = window.location.protocol + '//' + window.location.host;
                        var imageUrl = baseUrl + '/api/file/get?filename=' + response.data;
                        
                        // 插入绝对路径的图片到编辑器
                        $('#mailContentEditor').summernote('insertImage', imageUrl);
                        
                        console.log('【邮件图片上传】已插入绝对路径图片：' + imageUrl);
                    } else {
                        alert('图片上传失败：' + response.message);
                    }
                },
                error: function() {
                    alert('图片上传失败，请重试');
                }
            });
        }

        // 添加附件到列表
        function addAttachmentToList(fileName, fileSize, filePath, status) {
            var sizeText = formatFileSize(fileSize);
            var statusText = '';
            var statusClass = '';
            
            switch(status) {
                case 'uploading':
                    statusText = '上传中...';
                    statusClass = 'uploading';
                    break;
                case 'success':
                    statusText = '上传成功';
                    statusClass = 'success';
                    break;
                case 'error':
                    statusText = '上传失败';
                    statusClass = 'error';
                    break;
            }
            
            var attachmentHtml = '<div class="attachment-item" data-filename="' + fileName + '">' +
                '<div class="attachment-info">' +
                    '<div class="attachment-name">' + fileName + '</div>' +
                    '<div class="attachment-size">' + sizeText + ' - <span class="status ' + statusClass + '">' + statusText + '</span></div>' +
                '</div>' +
                '<button type="button" class="attachment-remove" onclick="removeAttachment(\'' + fileName + '\')">删除</button>' +
                '</div>';
            
            $('#attachmentList').append(attachmentHtml);
        }
        
        // 更新附件状态
        function updateAttachmentStatus(fileName, filePath, status) {
            var attachmentItem = $('.attachment-item[data-filename="' + fileName + '"]');
            var statusSpan = attachmentItem.find('.status');
            
            switch(status) {
                case 'success':
                    statusSpan.text('上传成功').removeClass('uploading error').addClass('success');
                    attachmentItem.attr('data-filepath', filePath);
                    break;
                case 'error':
                    statusSpan.text('上传失败').removeClass('uploading success').addClass('error');
                    break;
            }
        }
        
        // 删除附件
        function removeAttachment(fileName) {
            $('.attachment-item[data-filename="' + fileName + '"]').remove();
            
            // 从附件列表中删除
            attachmentList = attachmentList.filter(function(item) {
                return item.fileName !== fileName;
            });
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            var k = 1024;
            var sizes = ['Bytes', 'KB', 'MB', 'GB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        // 创建群发任务
        function createBatchTask() {
            var batchName = $('#batchName').val().trim();
            var senderConfigId = $('#senderConfig').val();
            var senderName = $('#senderName').val().trim();
            var subject = $('#subject').val().trim();
            var content = $('#mailContentEditor').summernote('code'); // 获取富文本内容
            var recipientsText = $('#recipients').val().trim();

            if (!batchName || !senderConfigId || !senderName || !subject || !content || !recipientsText) {
                alert('请填写所有必填字段！');
                return;
            }

            // 解析收件人列表
            var recipients = parseRecipients(recipientsText);
            if (recipients.length === 0) {
                alert('请至少输入一个有效的收件人邮箱！');
                return;
            }
            if (recipients.length > 100) {
                alert('收件人数量不能超过100个！');
                return;
            }

            var mailBatchSendBo = {
                batchName: batchName,
                senderConfigId: senderConfigId,
                senderName: senderName,
                subject: subject,
                content: content,
                recipients: recipients,
                attachments: attachmentList // 添加附件列表
            };

            // 发送请求
            $.ajax({
                url: '/api/mail/batch/create',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(mailBatchSendBo),
                success: function(response) {
                    if (response.code === 200) {
                        alert('任务创建成功！');
                        // 清空表单
                        $('#mailForm')[0].reset();
                        $('#mailContentEditor').summernote('reset');
                        $('#attachmentList').empty();
                        attachmentList = [];
                        loadTaskList();
                    } else {
                        alert('任务创建失败：' + response.message);
                    }
                },
                error: function() {
                    alert('创建任务时发生错误，请稍后重试！');
                }
            });
        }

        // 解析收件人列表
        function parseRecipients(text) {
            var lines = text.split('\n');
            var recipients = [];
            
            for (var i = 0; i < lines.length; i++) {
                var line = lines[i].trim();
                if (line === '') continue;
                
                var parts = line.split(',');
                var email = parts[0].trim();
                var name = parts.length > 1 ? parts[1].trim() : '';
                
                // 简单的邮箱格式验证
                if (email && isValidEmail(email)) {
                    recipients.push({
                        email: email,
                        name: name
                    });
                }
            }
            
            return recipients;
        }

        // 验证邮箱格式
        function isValidEmail(email) {
            var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return re.test(email);
        }

        // 加载任务列表
        function loadTaskList() {
            $.ajax({
                url: '/api/mail/batch/list',
                type: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        renderTaskList(response.data);
                    } else {
                        console.error('加载任务列表失败：' + response.message);
                    }
                },
                error: function() {
                    console.error('加载任务列表时发生错误');
                }
            });
        }

        // 渲染任务列表
        function renderTaskList(tasks) {
            var html = '';
            
            if (tasks.length === 0) {
                html = '<div style="text-align: center; color: #666; padding: 50px;">暂无群发任务</div>';
            } else {
                for (var i = 0; i < tasks.length; i++) {
                    var task = tasks[i];
                    html += renderTaskItem(task);
                }
            }
            
            $('#taskList').html(html);
        }

        // 渲染单个任务项
        function renderTaskItem(task) {
            var progressPercent = task.progressPercent || 0;
            var statusClass = 'status-' + task.status;
            
            var html = '<div class="task-item">' +
                '<div class="task-header">' +
                    '<div class="task-title">' + task.batchName + '</div>' +
                    '<div class="task-status ' + statusClass + '">' + task.statusDesc + '</div>' +
                '</div>' +
                '<div class="task-meta">' +
                    '主题: ' + task.subject + ' | ' +
                    '发送者: ' + task.senderName + ' | ' +
                    '创建时间: ' + formatDateTime(task.createTime) +
                    (task.retryCount > 0 ? ' | 重试次数: ' + task.retryCount : '') +
                '</div>' +
                '<div class="task-progress">' +
                    '<div class="progress-bar">' +
                        '<div class="progress-fill" style="width: ' + progressPercent + '%"></div>' +
                    '</div>' +
                    '<div style="margin-top: 5px; font-size: 12px; color: #666;">' +
                        '总数: ' + task.totalCount + ' | ' +
                        '成功: ' + (task.successCount || 0) + ' | ' +
                        '失败: ' + (task.failedCount || 0) + ' | ' +
                        '进度: ' + progressPercent.toFixed(1) + '%' +
                    '</div>' +
                '</div>' +
                '<div class="task-actions">';
            
            if (task.status === 'pending') {
                html += '<button class="btn" onclick="startBatchSend(' + task.id + ')">开始发送</button>';
                html += '<button class="btn btn-danger" onclick="cancelBatchSend(' + task.id + ')">取消任务</button>';
            } else if (task.status === 'sending' || task.status === 'retrying') {
                html += '<button class="btn btn-danger" onclick="cancelBatchSend(' + task.id + ')">取消发送</button>';
            } else if (task.status === 'completed' && task.failedCount > 0) {
                var retryCount = task.retryCount || 0;
                if (retryCount < 3) {
                    html += '<button class="btn" onclick="retryBatchSend(' + task.id + ')">重试失败邮件 (' + task.failedCount + '个)</button>';
                }
            }
            
            html += '<button class="btn btn-info" onclick="viewTaskDetail(' + task.id + ')">查看详情</button>';
            html += '</div></div>';
            
            return html;
        }

        // 开始发送
        function startBatchSend(batchId) {
            if (!confirm('确定要开始发送这个邮件群发任务吗？')) {
                return;
            }

            $.ajax({
                url: '/api/mail/batch/start/' + batchId,
                type: 'POST',
                success: function(response) {
                    if (response.code === 200) {
                        alert('邮件群发任务已开始执行！');
                        loadTaskList();
                    } else {
                        alert('启动任务失败：' + response.message);
                    }
                },
                error: function() {
                    alert('启动任务时发生错误，请稍后重试！');
                }
            });
        }

        // 重试发送
        function retryBatchSend(batchId) {
            if (!confirm('确定要重试这个邮件群发任务吗？只会重新发送失败的邮件。')) {
                return;
            }

            $.ajax({
                url: '/api/mail/batch/retry/' + batchId,
                type: 'POST',
                success: function(response) {
                    if (response.code === 200) {
                        alert('邮件群发任务已开始重试！');
                        loadTaskList();
                    } else {
                        alert('重试任务失败：' + response.message);
                    }
                },
                error: function() {
                    alert('重试任务时发生错误，请稍后重试！');
                }
            });
        }

        // 取消发送函数
        function cancelBatchSend(batchId) {
            if (!confirm('确定要取消这个邮件群发任务吗？')) {
                return;
            }

            $.ajax({
                url: '/api/mail/batch/cancel/' + batchId,
                type: 'POST',
                success: function(response) {
                    if (response.code === 200) {
                        alert('任务已取消！');
                        loadTaskList();
                    } else {
                        alert('取消任务失败：' + response.message);
                    }
                },
                error: function() {
                    alert('取消任务时发生错误，请稍后重试！');
                }
            });
        }

        // 查看任务详情
        function viewTaskDetail(batchId) {
            $.ajax({
                url: '/api/mail/batch/detail/' + batchId,
                type: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        showTaskDetail(response.data);
                    } else {
                        alert('获取任务详情失败：' + response.message);
                    }
                },
                error: function() {
                    alert('获取任务详情时发生错误！');
                }
            });
        }

        // 显示任务详情
        function showTaskDetail(task) {
            var detailHtml = '<h3>任务详情</h3>' +
                '<p><strong>任务名称：</strong>' + task.batchName + '</p>' +
                '<p><strong>邮件主题：</strong>' + task.subject + '</p>' +
                '<p><strong>发送者：</strong>' + task.senderName + '</p>' +
                '<p><strong>状态：</strong>' + task.statusDesc + '</p>' +
                '<p><strong>总数：</strong>' + task.totalCount + '</p>' +
                '<p><strong>成功：</strong>' + (task.successCount || 0) + '</p>' +
                '<p><strong>失败：</strong>' + (task.failedCount || 0) + '</p>';
                
            if (task.startedAt) {
                detailHtml += '<p><strong>开始时间：</strong>' + formatDateTime(task.startedAt) + '</p>';
            }
            if (task.completedAt) {
                detailHtml += '<p><strong>完成时间：</strong>' + formatDateTime(task.completedAt) + '</p>';
            }
            if (task.errorMessage) {
                detailHtml += '<p><strong>错误信息：</strong>' + task.errorMessage + '</p>';
            }
            
            detailHtml += '<h4>邮件内容预览</h4>' +
                '<div style="border: 1px solid #ddd; padding: 10px; background: #f9f9f9; max-height: 300px; overflow-y: auto;">' + 
                '<iframe srcdoc="' + task.content.replace(/"/g, '&quot;') + '" style="width: 100%; height: 200px; border: none;"></iframe>' +
                '</div>' +
                '<h4>邮件内容源码</h4>' +
                '<div style="border: 1px solid #ddd; padding: 10px; background: #f5f5f5; max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 12px;">' + 
                task.content.replace(/</g, '&lt;').replace(/>/g, '&gt;') + 
                '</div>';
            
            if (task.sendDetails && task.sendDetails.length > 0) {
                detailHtml += '<h4>发送详情</h4><table border="1" style="width: 100%; border-collapse: collapse;">' +
                    '<tr><th>收件人邮箱</th><th>收件人姓名</th><th>发送状态</th><th>发送时间</th><th>错误信息</th></tr>';
                
                for (var i = 0; i < task.sendDetails.length; i++) {
                    var detail = task.sendDetails[i];
                    detailHtml += '<tr>' +
                        '<td>' + detail.recipientEmail + '</td>' +
                        '<td>' + (detail.recipientName || '') + '</td>' +
                        '<td>' + getStatusText(detail.sendStatus) + '</td>' +
                        '<td>' + (detail.sentAt ? formatDateTime(detail.sentAt) : '') + '</td>' +
                        '<td>' + (detail.errorMessage || '') + '</td>' +
                        '</tr>';
                }
                detailHtml += '</table>';
            }
            
            // 创建模态框显示详情
            var modal = $('<div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">' +
                '<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 5px; max-width: 80%; max-height: 80%; overflow: auto;">' +
                detailHtml +
                '<div style="text-align: center; margin-top: 20px;"><button class="btn" onclick="$(this).closest(\'[style*=fixed]\').remove()">关闭</button></div>' +
                '</div></div>');
            
            $('body').append(modal);
        }

        // 获取状态文本
        function getStatusText(status) {
            switch(status) {
                case 'pending': return '等待发送';
                case 'success': return '发送成功';
                case 'failed': return '发送失败';
                default: return status;
            }
        }

        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '';
            var date = new Date(dateTime);
            return date.getFullYear() + '-' + 
                   (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                   date.getDate().toString().padStart(2, '0') + ' ' +
                   date.getHours().toString().padStart(2, '0') + ':' + 
                   date.getMinutes().toString().padStart(2, '0') + ':' + 
                   date.getSeconds().toString().padStart(2, '0');
        }
    </script>
</body>
</html>